package com.ocean.resources.service.impl;

import java.io.File;
import java.util.*;

import com.ocean.common.core.domain.Ztree;
import com.ocean.common.core.domain.entity.SysRole;
import com.ocean.common.core.domain.entity.SysUser;
import com.ocean.common.utils.ShiroUtils;
import com.ocean.resources.domain.OResources;
import com.ocean.resources.mapper.OResourcesMapper;
import com.ocean.resources.service.IOResourcesService;
import com.ocean.system.service.ISysConfigService;
import com.ocean.system.service.ISysDictDataService;
import com.ocean.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ocean.common.core.text.Convert;

/**
 * 资源目录信息Service业务层处理
 *
 * @author ocean
 * @date 2022-12-22
 */
@Service
public class OResourcesServiceImpl implements IOResourcesService
{
    @Autowired
    private OResourcesMapper oResourcesMapper;
    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询资源目录信息
     *
     * @param id 资源目录信息主键
     * @return 资源目录信息
     */
    @Override
    public OResources selectOResourcesById(Long id)
    {
        return oResourcesMapper.selectOResourcesById(id);
    }

    /**
     * 查询资源目录信息列表
     *
     * @param oResources 资源目录信息
     * @return 资源目录信息
     */
    @Override
    public List<OResources> selectOResourcesList(OResources oResources)
    {
        List<OResources> list = oResourcesMapper.selectOResourcesList(oResources);
        return list;
    }

    /**
     * 新增资源目录信息
     *
     * @param oResources 资源目录信息
     * @return 结果
     */
    @Override
    public int insertOResources(OResources oResources) {
        return oResourcesMapper.insertOResources(oResources);
    }
    @Override
    public String insertOResources(OResources oResources,String dirPath)
    {
        String msg = "资源目录表添加成功";
        SysUser sysUser = ShiroUtils.getSysUser();
        if (oResources.getParentId() == null){
            oResources.setParentId(Long.valueOf(0));
        }
        oResources.setDepartId(sysUser.getDeptId().toString());
        oResources.setCreateName(sysUser.getUserName());
        oResources.setCreateBy(sysUser.getLoginName());
        oResources.setCreateDate(new Date());
        //创建目录
        Object o = createFile(oResources,dirPath);
        if (o instanceof OResources){
            oResources = (OResources) o;
        }else if (o instanceof String){
            return (String) o;
        }
        oResourcesMapper.insertOResources(oResources);
        return msg;
    }

    /**
     * 修改资源目录信息
     *
     * @param oResources 资源目录信息
     * @return 结果
     */
    @Override
    public int updateOResources(OResources oResources){
        return oResourcesMapper.updateOResources(oResources);
    }
    @Override
    public String updateOResources(OResources oResources,String newPath)
    {
        String msg = "资源目录表修改成功";
        if (oResources.getParentId() == null){
            oResources.setParentId(Long.valueOf(0));
        }
        SysUser sysUser = ShiroUtils.getSysUser();
        oResources.setUpdateBy(sysUser.getLoginName());
        oResources.setUpdateDate(new Date());
        oResources.setUpdateName(sysUser.getUserName());
        Object o = updateFile(oResources,newPath);
        if (o instanceof String){
            msg = (String)o;
        }else if ((int)o < 0){
            msg = "修改文件夹失败";
        }
        return msg;
    }

    /**
     * 批量删除资源目录信息
     *
     * @param ids 需要删除的资源目录信息主键
     * @return 结果
     */
    @Override
    public int deleteOResourcesByIds(String ids)
    {
        return oResourcesMapper.deleteOResourcesByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除资源目录信息信息
     *
     * @param id 资源目录信息主键
     * @return 结果
     */
    @Override
    public String deleteOResourcesById(Long id)
    {
        try {
            String msg = "资源目录被引用不能删除";
            OResources r = new OResources();
            r.setParentId(id);
            List<OResources> list = oResourcesMapper.selectOResourcesList(r);
            if (list.size() <= 0) {
                OResources resources = oResourcesMapper.selectOResourcesById(id);
                boolean b = deleteDir(new File(resources.getResourcesDirPath()));
                if (!b) return msg;
                int i = oResourcesMapper.deleteOResourcesById(id);
                if (i > 0) msg = "删除成功";
            }
            return msg;
        }catch (Exception e){
            return "删除失败";
        }
    }

    /**
     * 查询资源目录信息树列表
     *
     * @return 所有资源目录信息信息
     */
    @Override
    public List<Ztree> selectOResourcesTree()
    {
        List<OResources> oResourcesList = oResourcesMapper.selectOResourcesList(new OResources());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (OResources oResources : oResourcesList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(oResources.getId());
            ztree.setpId(oResources.getParentId());
            ztree.setName(oResources.getResourcesName());
            ztree.setTitle(oResources.getResourcesName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 创建目录
     * @param resources
     * @return
     */
    private Object createFile(OResources resources,String dirPath){
        try {
            if (resources.getParentId() != 0) {
                OResources pRes = oResourcesMapper.selectOResourcesById(resources.getParentId());
                dirPath = pRes.getResourcesDirPath();
            }
            dirPath += "/" + resources.getResourcesDirPath();
            File file = new File(dirPath);
            if (!file.exists()) file.mkdirs();
            resources.setResourcesDirPath(dirPath);
            return resources;
        }catch (Exception e){
            return "创建文件夹失败";
        }
    }

    private Object updateFile(OResources resources,String newPath) {
            if (resources.getParentId() != 0){
                OResources pRes = oResourcesMapper.selectOResourcesById(resources.getParentId());
                newPath = pRes.getResourcesDirPath();
            }
            newPath += "/" + resources.getResourcesDirPath();
            String oldPath = oResourcesMapper.selectOResourcesById(resources.getId()).getResourcesDirPath();
            if (!newPath.equals(oldPath)) {
                List<OResources> list = oResourcesMapper.selectOResourcesList(new OResources());
                //获取下属所有子目录(包含当前)
                List<OResources> childResources = this.selectOResourcesChildsById(list, resources.getId());
                for (OResources childResource : childResources) {
                    String newChildPath = childResource.getResourcesDirPath().replace(oldPath, newPath);
                    File file = new File(newChildPath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    childResource.setResourcesDirPath(newChildPath);
                    if (childResource.getId().equals(resources.getId())){
                        childResource.setParentId(resources.getParentId());
                        childResource.setResourcesName(resources.getResourcesName());
                        childResource.setResourcesRemark(resources.getResourcesRemark());
                    }
                }
                int i = oResourcesMapper.updateOResourcesList(childResources);
                return i;
            }else {
                return oResourcesMapper.updateOResources(resources);
            }
    }

    /**
     * 获取下属所有子目录
     * @param list
     * @param id
     * @return
     */
    private List<OResources> selectOResourcesChildsById(List<OResources> list,Long id) {
        List<OResources> result = new ArrayList<>();
        for (OResources resources : list) {
            if (resources.getId().equals(id)) result.add(resources);
            else if (resources.getParentId().equals(id)){
//                result.add(resources);
                List<OResources> resList = selectOResourcesChildsById(list, resources.getId());
                result.addAll(resList);
            }
        }
        return result;
    }

    /**
     * 删除目录
     * @param dir
     * @return
     */
    private boolean deleteDir(File dir) throws Exception {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}
